package com.heima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.mapper.WMMapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.service.WMUserService;
import com.heima.utils.common.HutoolJWT;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author chenshan
 */
@Service
public class WMUserServiceImpl extends ServiceImpl<WMMapper, WmUser>
        implements WMUserService {

    @Override
    public ResponseResult loginAuth(WmLoginDto loginDto) {
        // 校验用户名是否为空
        if (!StrUtil.isAllNotBlank(loginDto.getName(), loginDto.getPassword())) {
            // 返回手机号码不合法
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空~");
        }

        WmUser wmUser = getOne(Wrappers.lambdaQuery(WmUser.class).eq(WmUser::getName, loginDto.getName()));
        // 用户不存在
        if (ObjectUtil.isNull(wmUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 和数据库中的密码做对比
        String pass = SecureUtil.md5(loginDto.getPassword() + wmUser.getSalt());
        if (!StrUtil.equals(pass, wmUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 判断账号是否被禁用
        if (wmUser.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        // 生成Token 并 返回
        HashMap<String, Object> mm = new HashMap<>();
        mm.put("id", wmUser.getId());
        String token = HutoolJWT.createToken(mm);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);

        wmUser.setPassword("");
        wmUser.setPassword("");
        wmUser.setSalt("");
        hashMap.put("user", wmUser);

        return ResponseResult.okResult(hashMap);
    }

}




